package com.meilingcloud.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilingcloud.system.domain.SysSeq;
import com.meilingcloud.system.mapper.SysSeqMapper;
import com.meilingcloud.system.service.ISysSeqService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 编码规则Service业务层处理
 *
 * @author chenl
 * @date 2021-08-25
 */
@Service
public class SysSeqServiceImpl extends ServiceImpl<SysSeqMapper, SysSeq> implements ISysSeqService {

    private final String ACTIVE_STATUS = "1";
    private final String UNACTIVE_STATUS = "0";

    @Override
    public List<SysSeq> queryList(SysSeq sysSeq) {
        LambdaQueryWrapper<SysSeq> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(sysSeq.getSeqName())) {
            lqw.like(SysSeq::getSeqName, sysSeq.getSeqName());
        }
        if (StringUtils.isNotBlank(sysSeq.getSeqDetail())) {
            lqw.eq(SysSeq::getSeqDetail, sysSeq.getSeqDetail());
        }
        if (StringUtils.isNotBlank(sysSeq.getSeqCode())) {
            lqw.eq(SysSeq::getSeqCode, sysSeq.getSeqCode());
        }
        if (StringUtils.isNotBlank(sysSeq.getDelimiter())) {
            lqw.eq(SysSeq::getDelimiter, sysSeq.getDelimiter());
        }
        if (StringUtils.isNotBlank(sysSeq.getResetRule())) {
            lqw.eq(SysSeq::getResetRule, sysSeq.getResetRule());
        }
        if (StringUtils.isNotBlank(sysSeq.getActive())) {
            lqw.eq(SysSeq::getActive, sysSeq.getActive());
        }
        return this.list(lqw);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean activeSeq(SysSeq sysSeq) {
        // 若存在其他开启规则，则置为关闭
        List<SysSeq> list = this.list(new LambdaQueryWrapper<SysSeq>().eq(SysSeq::getActive, ACTIVE_STATUS));
        List<SysSeq> collect = list.stream().map(t -> {
            t.setActive(UNACTIVE_STATUS);
            return t;
        }).collect(Collectors.toList());
        this.updateBatchById(collect);

        sysSeq.setActive("1");
        return this.updateById(sysSeq);
    }

    @Override
    public SysSeq getActive() {
        SysSeq sysSeq = this.getOne(new LambdaQueryWrapper<SysSeq>().eq(SysSeq::getActive, ACTIVE_STATUS).last("limit 1"));
        return sysSeq;
    }
}
